package com.novel.resource.qiniu.autoConfigurer;

import com.novel.resource.qiniu.QiniuClient;
import com.novel.resource.qiniu.config.QiniuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Arrays;

/**
 * qiniu 客户端工厂
 *
 * @author novel
 * @date 2020/3/31
 */
@Slf4j
public class QiniuClientFactoryBean implements FactoryBean<QiniuClient>, InitializingBean, DisposableBean {
    private QiniuClient qiniuClient;
    private QiniuConfig qiniuConfig;

    public QiniuClientFactoryBean(QiniuConfig qiniuConfig) {
        this.qiniuConfig = qiniuConfig;
    }

    @Override
    public QiniuClient getObject() throws Exception {
        return this.qiniuClient;
    }

    @Override
    public Class<?> getObjectType() {
        return QiniuClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void destroy() throws Exception {
        qiniuClient.shutdown();
        log.info("qiniu 销毁...");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("qiniu 初始化...");
        this.qiniuClient = new QiniuClient(this.qiniuConfig);
        String[] buckets = this.qiniuClient.getBucketManager().buckets();
        if (!Arrays.asList(buckets).contains(this.qiniuConfig.getBucketName())) {
            this.qiniuClient.getBucketManager().createBucket(this.qiniuConfig.getBucketName(), this.qiniuConfig.getRegion().name());
        }
    }
}
